package com.ruoyi.system.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.domain.RedisInfo;
import com.ruoyi.system.domain.RedisVo;
import com.ruoyi.system.service.ISysRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wjialong
 */
@RestController
@RequestMapping("/server")
public class SysRedisController {
    @Autowired
    ISysRedisService redisService;


    /**
     * 获取所有的Redis服务器列表
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult iniRedisList() {
        List<RedisVo> redisList;
        try {
            redisList = redisService.iniRedisList();
        } catch (Exception e) {
            // 处理异常情况
            return AjaxResult.error("获取Redis服务器列表时发生错误：" + e.getMessage());
        }
        return AjaxResult.success(redisList);
    }

    /**
     * 根据redisId获取单个服务器的数据
     *
     * @param id
     * @return
     */
    @GetMapping
    public AjaxResult getRedisInfo(@RequestParam("redisId") String id) {
        RedisInfo redisInfo = redisService.getRedisInfo(id);
        if (redisInfo == null) {
            return AjaxResult.error("redis不存在");
        }
        return AjaxResult.success(redisInfo);
    }

    /**
     * 新增Redis服务器数据
     *
     * @param redisInfo
     * @return
     */
    @PostMapping
    public AjaxResult addRedis(@RequestBody RedisInfo redisInfo) {

        return AjaxResult.success(redisService.addRedis(redisInfo));
    }

    /**
     * 修改Redis服务器数据
     *
     * @param redisInfo
     * @return
     */
    @PutMapping
    public AjaxResult updateRedis(@RequestBody RedisInfo redisInfo) {
        redisService.updateRedis(redisInfo);
        return AjaxResult.success();
    }

    /**
     * 删除Redis服务器数据
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public AjaxResult deleteRedis(@RequestParam("redisId") String id) {
        redisService.deleteRedis(id);
        return AjaxResult.success();
    }

    /**
     * 获取id对应的数据库列表
     *
     * @param id
     * @return 返回的前端所需的树结构
     */
    @GetMapping("/dbs")
    public AjaxResult getDBList(@RequestParam("redisId") String id) {
        RedisInfo redisInfo = redisService.getRedisInfo(id);
        List<RedisVo> dbList = redisService.getDBList(redisInfo);
        if (dbList.size() == 0) {
            return AjaxResult.error("连接失败");
        }
        return AjaxResult.success(dbList);
    }

    /**
     * 测试连接
     *
     * @param redisInfo
     * @return
     */
    @PostMapping("/connect")
    public AjaxResult testConnect(@RequestBody RedisInfo redisInfo) {
        boolean connectAble = redisService.testConnect(redisService.getRedisTemplate(redisInfo, 0));
        if (connectAble) {
            return AjaxResult.success("测试连接成功");
        }
        return AjaxResult.success("测试连接失败");
    }
}
